<template>
    <div class="position-category-management">
        <pageTitle :title="'職位類別管理'" />

        <!-- 顶部操作栏 -->
        <div class="top-action-bar">
            <el-row :gutter="20" align="middle">
                <el-col :span="12">
                    <el-input placeholder="请输入類別名稱" v-model="searchQuery" class="search-input-with-button" clearable
                        @clear="handleSearch" @keyup.enter="handleSearch">
                        <template #append>
                            <el-button type="primary" @click="handleSearch">
                                <el-icon>
                                    <Search />
                                </el-icon>
                            </el-button>
                        </template>
                    </el-input>
                </el-col>
                <el-col :span="12" class="action-buttons">
                    <el-button type="primary" @click="addRootCategory">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        <span>新增類別</span>
                    </el-button>
                    <el-button type="danger" @click="batchDelete" :disabled="selectedCategories.length === 0">
                        <el-icon>
                            <Delete />
                        </el-icon>
                        <span>批量删除</span>
                    </el-button>
                </el-col>
            </el-row>
        </div>

        <!-- 類別树表格 -->
        <div class="category-table">
            <el-table :data="filteredCategories" style="width: 100%" row-key="id" v-loading="loading"
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" :default-expand-all="false"
                class="no-border-table" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" :selectable="isSelectable" />
                <el-table-column prop="name" label="類別名稱" width="300" />
                <el-table-column prop="description" label="描述" />
                <el-table-column label="操作" width="280" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="addSubCategory(row)">
                            添加下級類別
                        </el-button>
                        <el-button type="success" size="small" @click="editCategory(row)">
                            编辑
                        </el-button>
                        <el-button type="danger" size="small" @click="deleteCategory(row)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 新增/编辑類別对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
            <el-form :model="categoryForm" :rules="categoryRules" ref="categoryFormRef" label-width="100px">
                <el-form-item label="類別名稱" prop="name">
                    <el-input v-model="categoryForm.name" placeholder="请输入類別名稱" />
                </el-form-item>
                <el-form-item label="上級類別" v-if="isSubCategory">
                    <el-input v-model="categoryForm.parentName" disabled />
                </el-form-item>
                <el-form-item label="描述">
                    <el-input v-model="categoryForm.description" type="textarea" :rows="3" placeholder="请输入描述信息" />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitCategoryForm">确定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { Search, Plus, Delete } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import pageTitle from "@/components/pageTitle/pageTitle.vue";

// 响应式数据
const searchQuery = ref('');
const loading = ref(false);
const selectedCategories = ref([]);

// 類別数据
const categories = ref([
    {
        id: 1,
        name: '技术类',
        description: '技术研发相关職位',
        expanded: false,
        children: [
            { id: 4, name: '前端开发', description: 'Web前端开发工程师' },
            { id: 5, name: '后端开发', description: '服务器端开发工程师' },
            { id: 6, name: '测试工程师', description: '软件测试工程师' }
        ]
    },
    {
        id: 2,
        name: '产品类',
        description: '产品设计与管理職位',
        expanded: false,
        children: [
            { id: 7, name: '产品经理', description: '负责产品规划与管理' },
            { id: 8, name: 'UI设计师', description: '用户界面设计师' }
        ]
    },
    {
        id: 3,
        name: '运营类',
        description: '市场运营相关職位',
        expanded: false,
        children: [
            { id: 9, name: '市场运营', description: '市场推广与运营' },
            { id: 10, name: '内容运营', description: '内容创作与运营' }
        ]
    }
]);

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref('新增類別');
const isSubCategory = ref(false);
const categoryForm = ref({
    id: null,
    name: '',
    parentId: null,
    parentName: '',
    description: ''
});
const categoryRules = {
    name: [{ required: true, message: '请输入類別名稱', trigger: 'blur' }]
};
const categoryFormRef = ref(null);
const currentParent = ref(null);

// 计算属性
const filteredCategories = computed(() => {
    if (!searchQuery.value) {
        return categories.value;
    }
    const search = searchQuery.value.toLowerCase();
    return filterCategories(categories.value, search);
});

// 方法 - 递归过滤類別
const filterCategories = (categories, search) => {
    return categories.filter(category => {
        const matches = category.name.toLowerCase().includes(search) ||
            (category.description && category.description.toLowerCase().includes(search));

        if (category.children && category.children.length > 0) {
            const filteredChildren = filterCategories(category.children, search);
            if (filteredChildren.length > 0) {
                return true;
            }
        }

        return matches;
    }).map(category => {
        if (category.children && category.children.length > 0) {
            return {
                ...category,
                children: filterCategories(category.children, search)
            };
        }
        return category;
    });
};

// 方法 - 添加根類別
const addRootCategory = () => {
    dialogTitle.value = '新增類別';
    isSubCategory.value = false;
    categoryForm.value = {
        id: null,
        name: '',
        parentId: null,
        parentName: '',
        description: ''
    };
    dialogVisible.value = true;
};

// 方法 - 添加子類別
const addSubCategory = (row) => {
    dialogTitle.value = '新增子類別';
    isSubCategory.value = true;
    currentParent.value = row;
    categoryForm.value = {
        id: null,
        name: '',
        parentId: row.id,
        parentName: row.name,
        description: ''
    };
    dialogVisible.value = true;
};

// 方法 - 编辑類別
const editCategory = (row) => {
    dialogTitle.value = '编辑類別';
    isSubCategory.value = false;
    categoryForm.value = {
        id: row.id,
        name: row.name,
        parentId: null,
        parentName: '',
        description: row.description || ''
    };
    dialogVisible.value = true;
};

// 方法 - 删除類別
const deleteCategory = (row) => {
    ElMessageBox.confirm(`确定要删除類別「${row.name}」${row.children?.length ? '及其所有子類別' : ''}吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        deleteCategoryFromTree(row.id);
        // 同时从已选列表中移除
        selectedCategories.value = selectedCategories.value.filter(item => item.id !== row.id);
        ElMessage.success('删除成功');
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
};

// 方法 - 批量删除
const batchDelete = () => {
    if (selectedCategories.value.length === 0) {
        ElMessage.warning('请至少选择一个子類別');
        return;
    }

    const names = selectedCategories.value.map(c => c.name).join('、');
    ElMessageBox.confirm(`确定要删除选中的 ${selectedCategories.value.length} 个子類別吗? (${names})`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        selectedCategories.value.forEach(category => {
            deleteCategoryFromTree(category.id);
        });
        selectedCategories.value = [];
        ElMessage.success('批量删除成功');
    }).catch(() => {
        ElMessage.info('已取消批量删除');
    });
};

// 方法 - 从树中删除類別
const deleteCategoryFromTree = (id, tree = categories.value) => {
    for (let i = 0; i < tree.length; i++) {
        if (tree[i].id === id) {
            tree.splice(i, 1);
            return true;
        }
        if (tree[i].children && tree[i].children.length > 0) {
            if (deleteCategoryFromTree(id, tree[i].children)) {
                return true;
            }
        }
    }
    return false;
};

// 方法 - 提交類別表单
const submitCategoryForm = () => {
    categoryFormRef.value.validate((valid) => {
        if (valid) {
            if (categoryForm.value.id) {
                // 编辑现有類別
                updateCategoryInTree(categoryForm.value);
                ElMessage.success('類別更新成功');
            } else {
                // 新增類別
                const newId = Math.max(...getAllCategoryIds(), 0) + 1;
                const newCategory = {
                    id: newId,
                    name: categoryForm.value.name,
                    description: categoryForm.value.description,
                    expanded: false
                };

                if (isSubCategory.value) {
                    // 添加子類別
                    addCategoryToParent(newCategory, categoryForm.value.parentId);
                } else {
                    // 添加根類別
                    categories.value.push(newCategory);
                }
                ElMessage.success('類別添加成功');
            }
            dialogVisible.value = false;
        }
    });
};

// 方法 - 获取所有類別ID
const getAllCategoryIds = () => {
    const ids = [];
    const traverse = (nodes) => {
        nodes.forEach(node => {
            ids.push(node.id);
            if (node.children) {
                traverse(node.children);
            }
        });
    };
    traverse(categories.value);
    return ids;
};

// 方法 - 更新树中的類別
const updateCategoryInTree = (updatedCategory, tree = categories.value) => {
    for (let i = 0; i < tree.length; i++) {
        if (tree[i].id === updatedCategory.id) {
            tree[i].name = updatedCategory.name;
            tree[i].description = updatedCategory.description;
            return true;
        }
        if (tree[i].children && tree[i].children.length > 0) {
            if (updateCategoryInTree(updatedCategory, tree[i].children)) {
                return true;
            }
        }
    }
    return false;
};

// 方法 - 添加類別到父類別
const addCategoryToParent = (newCategory, parentId, tree = categories.value) => {
    for (let i = 0; i < tree.length; i++) {
        if (tree[i].id === parentId) {
            if (!tree[i].children) {
                tree[i].children = [];
            }
            tree[i].children.push(newCategory);
            return true;
        }
        if (tree[i].children && tree[i].children.length > 0) {
            if (addCategoryToParent(newCategory, parentId, tree[i].children)) {
                return true;
            }
        }
    }
    return false;
};

// 方法 - 处理选择变化
const handleSelectionChange = (selection) => {
    selectedCategories.value = selection;
};

// 方法 - 判断是否可选（只有子類別可选）
const isSelectable = (row) => {
    // 检查是否有父級（即是否为子類別）
    return hasParent(row.id);
};

// 方法 - 检查類別是否有父級
const hasParent = (id, tree = categories.value) => {
    for (let i = 0; i < tree.length; i++) {
        if (tree[i].children) {
            for (let j = 0; j < tree[i].children.length; j++) {
                if (tree[i].children[j].id === id) {
                    return true;
                }
                // 递归检查更深层次的子類別
                if (tree[i].children[j].children && hasParent(id, tree[i].children)) {
                    return true;
                }
            }
        }
    }
    return false;
};

// 方法 - 搜索
const handleSearch = () => {
    // 搜索逻辑已在计算属性中处理
};

// 生命周期钩子
onMounted(() => {
    // 可以在这里加载初始数据
});
</script>

<style scoped lang="less">
.position-category-management {
    padding: 20px;
    background-color: #fff;

    .top-action-bar {
        margin-bottom: 20px;
        padding: 16px 24px;
        background-color: #fff;
        border-radius: 8px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
        margin-top: 20px;

        .search-input-with-button {
            max-width: 500px;

            .el-input-group__append {
                background-color: var(--el-color-primary);
                color: white;
                border: none;

                &:hover {
                    opacity: 0.9;
                }
            }
        }

        .action-buttons {
            display: flex;
            justify-content: flex-end;
            gap: 12px;

            .el-button {
                display: inline-flex;
                align-items: center;
                gap: 6px;
            }
        }
    }

    .category-table {
        padding: 16px;
        border: 1px solid #ebeef5;
        border-radius: 8px;
        background-color: #fff;

        .no-border-table {

            :deep(.el-table__header),
            :deep(.el-table__body),
            :deep(.el-table__row),
            :deep(.el-table__cell) {
                border: none !important;
            }

            :deep(.el-table__header th) {
                background-color: #f4f8ff;
                font-weight: 600;
                padding: 20px;
            }

            :deep(.el-table__row):hover td {
                background-color: #f5f7fa !important;
            }
        }

        .category-name {
            display: flex;
            align-items: center;
            cursor: pointer;

            .expand-icon {
                margin-right: 8px;
                color: #909399;
            }

            .expand-icon-placeholder {
                width: 16px;
                margin-right: 8px;
            }
        }
    }
}
</style>